package com.ourway;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class LoginActivity extends Activity{
	
	private ImageButton buttonConnFacebook;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
		
		Session session = Session.getActiveSession();
		if(session == null){
			if(savedInstanceState != null){
				session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
			}
			if(session == null){
				session = new Session(this);
			}
			Session.setActiveSession(session);
			if(session.getState().equals(SessionState.CREATED_TOKEN_LOADED)){
				session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
			}
		}
		
		buttonConnFacebook = (ImageButton) findViewById(R.id.btnFacebook);
		buttonConnFacebook.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onClickFacbookButton();
			}
		});
	}
	
	@Override
	public void onStart(){
		super.onStart();
		Session.getActiveSession().addCallback(statusCallback);
	}
	
	@Override
	public void onStop(){
		super.onStop();
		Session.getActiveSession().removeCallback(statusCallback);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		Session session = Session.getActiveSession();
		session.onActivityResult(this, requestCode, resultCode, data);
		
		if(session.isOpened()){
			startActivity(new Intent(this, MainActivity.class));
			finish();
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState){
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}

	private void onClickFacbookButton(){
		Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
	}
	
	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			// TODO Auto-generated method stub
			
		}
	};

}
